var models = require('../db/db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../db/sqlMap');

// var conn = mysql.createConnection(models.mysql);

// conn.connect();

var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.send('err');
    } else {
        console.log(ret);
        res.send(ret);
    }
}

var dateStr = function(str) {
    return new Date(str.slice(0,7));
}

// 增加用户接口
router.post('/addUser', (req, res) => {
    var sql = $sql.user.add;
    var params = '';
    req.on("data",function(chunk){
        params += chunk
    })
    req.on('end',function(){
        params = JSON.parse(params)
        conn.query(sql, [params.name, params.account, params.pass, params.checkPass,
                    params.email, params.phone, params.card, dateStr(params.birth), params.sex], function(err, result) {
            if (err) {
                console.log(err);
            }
            if (result) {
                jsonWrite(res, result);
            }
        })
    })
});

//查找用户接口

router.post('/login', (req, res) => {
    var sql_name = $sql.user.select_name;//数据库查询语句
    // var sql_password = $sql.user.select_password;
    var keywords = '';
    req.on("data",function(chunk){
        keywords += chunk
    })
    req.on("end",function(){
        keywords = JSON.parse(keywords)
        sql_name += ' where username="'+ keywords.name + '"';
        conn.query(sql_name, keywords.name, function(err, result) {
            if (err) {
                console.log(err);
            }
            if (result[0] === undefined) {
                res.send('-1')   //查询不出username，data 返回-1
            } else {
                res.cookie('id',result[0].id,{signed: true,maxAge: 900000})
                jsonWrite(res, result)
            }
        })
    })
});

//获取用户信息
router.get('/getUser', (req, res) => {
    try{
        var sql_name = $sql.user.select_name
        var params = req.query
        sql_name += ' where username="'+ params.name + '"'
        conn.query(sql_name, params.name, function(err, result) {
            if (err) {
                console.log(err);
            }
            if (result[0] === undefined) {
                res.send('-1')//查询不出username，data 返回-1
            } else {
                jsonWrite(res, result);
            }
        })
    }catch(err){

    }
    // try{
    //     // post请求
    //     var sql_name = $sql.user.select_name;
    //     var params = '';
    //     req.on("data",function(chunk){
    //         params += chunk
    //     })
    //     req.on("end",function(){
    //         params = JSON.parse(params)
    //         sql_name += ' where username="'+ params.name + '"';
    //         conn.query(sql_name, params.name, function(err, result) {
    //             if (err) {
    //                 console.log(err);
    //             }
    //             if (result[0] === undefined) {
    //                 res.send('-1')//查询不出username，data 返回-1
    //             } else {
    //                 jsonWrite(res, result);
    //             }
    //         })
    //     })
    // }catch(err){
    //     console.log(err,'err')
    // }
});

//更新用户信息
router.post('/updateUser', (req, res) => {
    try{
        var sql_update = $sql.user.update_user
        var params = ''
        req.on("data",function(chunk){
            params += chunk
        })
        req.on('end',function () {
            params = JSON.parse(params)
            if (params.id) {
                sql_update  += " email = '" + params.email +
                                "',phone = '" + params.phone +
                                "',card = '" + params.card +
                                "',birth = '" + params.birth +
                                "',sex = '" + params.sex +
                                "' where id ='"+ params.id + "'";
            }    
            conn.query(sql_update, params.id, function(err, result) {
                if (err) {
                    console.log(err);
                }
                console.log(result);
                if (result.affectedRows === undefined) {
                    res.send('更新失败，请联系管理员')   //查询不出username，data 返回-1
                } else {
                    res.send('ok'); 
                }
            })
        })
    }catch(err){

    }
});

//更改密码
router.post('/modifyPassword', (req, res) => {
    try{
        var sql_modify = $sql.user.update_user
        var params = ''
        req.on("data",function(chunk){
            params += chunk
        })
        req.on('end',function(){
            params = JSON.parse(params)
            if (params.id) {
                sql_modify +=  " password = '" + params.pass +
                                "',repeatPass = '" + params.checkPass +
                                "' where id ='"+ params.id + "'";
            }
            conn.query(sql_modify, params.id, function(err, result) {
                if (err) {
                    console.log(err);
                }
                // console.log(result);
                if (result.affectedRows === undefined) {
                    res.send('修改密码失败，请联系管理员')   //查询不出username，data 返回-1
                } else {
                    res.send('ok'); 
                }
            })
        })
    }catch(err){

    }
});


module.exports = router;
